package com.jsb.laundry.common.utils.excel;

import com.alibaba.fastjson.JSON;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 可以触发浏览器下载文件。用于实现数据的导出。<br>
 *
 * 
 * @author caipeichao
 */
public class AttachmentResponse extends FilterOutputStream {

    private HttpServletResponse response;

    private HttpServletRequest request;

    private final String AGENT_MSIE = "msie";

    /**
     * @param request
     * @param response
     * @param filename 返回给浏览器的文件名称。不是临时文件名称。不要包含特殊字符，比如引号。null表示文件名由浏览器生成。
     * @param contentType MIME类型，比如text/html。
     */
    public AttachmentResponse(HttpServletRequest request, HttpServletResponse response, String filename, String contentType){
        // 初始化
        super(null);
        this.request = request;
        this.response = response;
        try {
            this.out = response.getOutputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 默认文件名由浏览器自动生成
        String contentDisposition = "attachment";
        if (filename != null) {
                String encodedFilename = urlEncode(filename);
                contentDisposition += String.format("; filename=\"%s\"", encodedFilename);
        }

        // 告诉浏览器下载文件
        response.reset();
        response.setContentType(contentType);
        response.addHeader("Content-Disposition", contentDisposition);
        response.setContentType("application/octet-stream");
//        response.addHeader("Access-Control-Allow-Origin","*");
    }

    /**
     * 返回下载出错原因给前端
     *
     * @param response
     * @param errorMsg
     */
    public static void writeDownloadErrorResponse(HttpServletResponse response, String errorMsg) {
        DownloadErrorResponse downloadErrorResponse = new DownloadErrorResponse();
        downloadErrorResponse.setMsg(errorMsg);
        try {
            IOUtils.write(JSON.toJSONString(downloadErrorResponse).getBytes("UTF-8"), response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

//    /**
//     * URL编码。
//     */
//    private String urlEncode(String x) {
//        try {
//            String agent = request.getHeader("USER-AGENT").toLowerCase();
//            if(agent.indexOf(AGENT_MSIE)>-1){
//                return URLEncoder.encode(x, "UTF-8");
//            }
//            else{  //firefox/safari不转码
//                return new String(x.getBytes(StandardCharsets.UTF_8), "ISO8859-1");
//            }
//        } catch (Exception ex) {
//            throw new RuntimeException(x);
//        }
//    }
    /**
     * URL编码。
     */
    private String urlEncode(String x) {
        try {
            return URLEncoder.encode(x, StandardCharsets.UTF_8.toString());
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException(x);
        }
    }

}
